package net.stogi.dsper.back.service.impl;

import java.util.Arrays;

import net.stogi.common.security.dto.PrincipalData;
import net.stogi.common.security.exception.AuthenticationException;
import net.stogi.common.security.service.AuthenticationService;
import net.stogi.dsper.api.model.User;
import net.stogi.dsper.back.dao.UserDao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("DsperBack.Service.AuthenticationService")
public class AuthenticationServiceImpl implements AuthenticationService {

	private final Logger log = LoggerFactory.getLogger(AuthenticationServiceImpl.class);

	@Autowired
	private UserDao userDao;

	@Override
	public PrincipalData getUserPrincipalData(String username) throws AuthenticationException {
		if (username == null) {
			log.error("Parameter 'username' is null");
			throw new IllegalArgumentException("Parameter 'username' can not be null");
		}

		// Load user from database.
		User user = userDao.loadByUsername(username);

		log.trace("User loaded form database: [user = '{}']", user);

		// Check user if not null.
		if (user == null) {
			log.warn("User with given login does not exist: [username = '{}']", username);
			throw new AuthenticationException("User not found in database");
		}

		// Create principal data.
		PrincipalData principalData = new PrincipalData();
		principalData.setUsername(user.getLogin());
		principalData.setPassword(user.getPassword());
		principalData.setRoles(Arrays.asList("ROLE_USER"));

		log.trace("PrincipalData created: [principalData = '{}']", principalData);

		return principalData;
	}
}
